﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using BizModels.GuestBook;
using HinokyWeb.SignalRHubs;
using IRepositories;
//using Microsoft.AspNet.SignalR;
using Repositories;
using ViewModels.GuestBookVM;
using WebLib;
using WebLib.AuthorizeService;
using ViewModels.CommonVM;

namespace HinokyWeb.Controllers
{
    public class GuestBookController : BaseController
    {
        private IGuestBookRepository _guestBookRepository;

        public GuestBookController()
        {
            _guestBookRepository = new GuestBookRepository();
        }

        [HttpGet]
        public ActionResult List(string location, int subKey, int pageSize)
        {
            ViewBag.Location = location;
            ViewBag.SubKey = subKey;

            var pageIndex = -1;

            var isAdmin = MemberInfo.Instance.IsSignIn && MemberInfo.Instance.UserRole.Contains("ADMIN");

            var dataList = _guestBookRepository.GetGuestBookList(location, subKey, pageIndex, pageSize, isAdmin);

            var modelData = CreateDataBindingList(dataList);

            if (IsAjaxRequest) return Json(new { GuestBookList = modelData.GuestBookList, LastIdx = modelData.GuestBookLastIdx }, JsonRequestBehavior.AllowGet);

            return View(modelData);
        }

        [HttpGet]
        public ActionResult More(string location, int subKey, int firstIdx, int pageSize)
        {
            ViewBag.Location = location;
            ViewBag.SubKey = subKey;

            var isAdmin = MemberInfo.Instance.IsSignIn && MemberInfo.Instance.UserRole.Contains("ADMIN");

            var dataList = _guestBookRepository.GetGuestBookList(location, subKey, firstIdx, pageSize, isAdmin);

            var modelData = CreateDataBindingList(dataList);

            return Json(new { GuestBookList = modelData.GuestBookList, LastIdx = modelData.GuestBookLastIdx }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult GetCapchaString()
        {
            var rdm = new Random();
            Session["CaptchaVal"] = rdm.Next(20);
            var returnValue = Session["CaptchaVal"].ToString();

            return Json(new { CapchaString = returnValue }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult Create(GuestBookCreateVM model)
        {
            if(Session["CaptchaVal"].ToString() != model.CaptcharResponse)
                return Json(new { Success = false, InvalidCaptcha = true });

            try
            {
                var data = new GuestBookInsT
                {
                    LocationCode = model.LocationCode,
                    SubKey = model.SubKey,
                    Comment = model.Comment,
                    GuestName = model.GuestName,
                    IPAddress = WebHelper.GetClientUserIP(),
                    IsPrivate = model.IsPrivate,
                    SecureEmailAddress = model.SecureEmailAddress
                };

                if (MemberInfo.Instance.IsSignIn && MemberInfo.Instance.UserRole.Contains("ADMIN"))
                {
                    data.GuestName = data.GuestName + " <img class='masterIcon' src='/Images/Shi-en_Castle_Sanctum_Logo.png' width='21' height='21' alt='Master' />";
                }

                var returnValue = _guestBookRepository.AddGuestBook(data);

                /** SignalR를 위한 코드
                if (returnValue > 0)
                    SendToClientNewGuestArticle(returnValue);
                 * */

                var returnData = GetGuestBookData(model.LocationCode, model.SubKey, returnValue);

                return Json(new { GuestBookData = returnData }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new { Success = false });
            }
        }

        [HttpPost]
        public ActionResult AddReply(GuestBookReplyCreateVM model)
        {
            if (Session["CaptchaVal"].ToString() != model.CaptcharResponse)
                return Json(new { Success = false, InvalidCaptcha = true });

            try
            {
                var data = new GuestBookInsT
                {
                    LocationCode = model.LocationCode,
                    SubKey = model.SubKey,
                    ParentIdx = model.ParentIdx,
                    Comment = model.Comment,
                    GuestName = model.GuestName,
                    IPAddress = WebHelper.GetClientUserIP(),
                    IsPrivate = false,
                    SecureEmailAddress = model.SecureEmailAddress
                };

                if (MemberInfo.Instance.IsSignIn && MemberInfo.Instance.UserRole.Contains("ADMIN"))
                {
                    data.GuestName = data.GuestName + "<img class='masterIcon' src='/Images/Shi-en_Castle_Sanctum_Logo.png' width='21' height='21' alt='Master' />";
                }

                var newIdx = _guestBookRepository.AddGuestBook(data);

                var replyData = GetGuestBookData(model.LocationCode, model.SubKey, newIdx);

                return Json(new { ReplyData = replyData }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new { Success = false });
            }
        }

        private GuestBookObjVM GetGuestBookData(string location, int subKey, int idx)
        {
            var data = _guestBookRepository.GetGuestBook(location, subKey, idx);

            if (data != null)
            {
                var returnData = new GuestBookListVM
                {
                    LocationCode = data.LocationCode,
                    SubKey = data.SubKey,
                    Idx = data.Idx,
                    Comment = data.Comment,
                    GuestName = data.GuestName,
                    InsertDate = data.InsertDate,
                    InsertDateString = data.InsertDate.ToString("yyyy-MM-dd"),
                    IsPrivate = data.IsPrivate,
                    IPAddress = data.IPAddress,
                    SecureEmailAddress = data.SecureEmailAddress
                };

                return returnData;
            }

            return null;
        }

        private static GuestBookMainVM CreateDataBindingList(List<GuestBookListT> dataList)
        {
            var modelData = new GuestBookMainVM();

            foreach (var dataItem in dataList)
            {
                var bookItem = new GuestBookListVM();

                bookItem.LocationCode = dataItem.LocationCode;
                bookItem.SubKey = dataItem.SubKey;
                bookItem.Idx = dataItem.Idx;
                bookItem.Comment = dataItem.Comment;
                bookItem.GuestName = dataItem.GuestName;
                bookItem.InsertDate = dataItem.InsertDate;
                bookItem.IsPrivate = dataItem.IsPrivate;
                bookItem.IPAddress = dataItem.IPAddress;
                bookItem.SecureEmailAddress = dataItem.SecureEmailAddress;
                bookItem.InsertDateString = dataItem.InsertDate.ToString("yyyy-MM-dd");

                foreach (var replyDataItem in dataItem.ReplyList)
                {
                    var replyItem = new GuestBookReplyListVM();

                    replyItem.LocationCode = replyDataItem.LocationCode;
                    replyItem.SubKey = replyDataItem.SubKey;
                    replyItem.Idx = replyDataItem.Idx;
                    replyItem.Comment = replyDataItem.Comment;
                    replyItem.GuestName = replyDataItem.GuestName;
                    replyItem.InsertDate = replyDataItem.InsertDate;
                    replyItem.IPAddress = replyDataItem.IPAddress;
                    replyItem.SecureEmailAddress = replyDataItem.SecureEmailAddress;
                    replyItem.InsertDateString = dataItem.InsertDate.ToString("yyyy-MM-dd");

                    bookItem.ReplyList.Add(replyItem);
                }

                modelData.GuestBookList.Add(bookItem);
            }

            var lastData = modelData.GuestBookList.LastOrDefault();
            if (lastData != null) modelData.GuestBookLastIdx = lastData.Idx;

            return modelData;
        }
    }
}
